from datetime import datetime
from django.db.models import Manager

class PublishedManager(Manager):
	"""
	A custom manager to return only published objects.
	"""
	use_for_related_fields = True
	
	def get_query_set(self):
		# distinct is needed for artist.photos, as this would include a photo
		# each time the artist contributed to it (e.g. both as make-up artist
		# and hair stylist).
		return super(PublishedManager, self).get_query_set().distinct().filter(published__lte = datetime.now())
	
def rst(input):
	"""
	Converts given reStructuredText markup into HTML
	"""
	from docutils.core import publish_parts
	return publish_parts(source = input, writer_name = 'html4css1')['fragment']

def markdown(input):
	"""
	Converts given markdown markup into HTML
	"""
	import markdown
	return markdown.markdown(input)

markup_choices = (
	("HTM", "XHTML"),
	("PLT", "plain text"),
	("MKD", "Markdown"),
	("RST", "reStructuredText"),
)
# maps markup slugs to converter functions
markup_converters = {
	"MKD" : markdown,
	"RST" : rst,
}

def convert_markup(input, markup):
	"""
	Converts given input text in given markup into HTML
	"""
	if markup == "HTM":
		return input
	elif markup == "PLT":
		return "<pre>" + input + "</pre>"
	else:
		return markup_converters[markup](input)
